<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单例模式</title>
</head>
<body>
<script>
    class Singleton {
        constructor() {
            // 静态属性，只属于类，而不属于实例，所以每次new 时，判断静态属性是否已经存在，如果存在就返回，否则就创建新的实例，并将静态属性指向这个实例
            if (Singleton.instance){
                return Singleton.instance
            } else {
                Singleton.instance = this
            }
        }
        static getInstance() {
            if(!this.instance) {
                this.instance = new Singleton()
                return this.instance
            } else {
                return this.instance
            }
        }
    }

    const s1 = new Singleton()
    const s2 = new Singleton()
    console.log(s1 === s2)
    console.log(s1 === s2)
    console.log(Singleton.getInstance() === s1)
    console.log(Singleton.getInstance() === s2)
    console.log(Singleton.getInstance() === Singleton.getInstance())
    console.log(s1.constructor)
</script>
</body>
</html>
